package pers.cz.quartz.job;

import pers.cz.commons.datasource.DbKeyHolder;
import pers.cz.mac.MacUtils;
import pers.cz.mapper.SystemJobLogMapper;
import pers.cz.model.SystemJobLog;
import pers.cz.pub.BeanHelper;
import pers.cz.pub.CpublicFunc;
import pers.cz.pub.SequenceEnum;
import pers.cz.spring.SpringContextUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

/**
 * Job核心类
 * @program: Quartz_New
 * @description: AbstractQuartzJob
 * @author: Cheng Zhi
 * @create: 2021-05-09 10:04
 **/
public abstract class AbstractQuartzJob implements Job {

    Logger logger = LoggerFactory.getLogger(AbstractQuartzJob.class);

    private static final String serverIp = MacUtils.getLocalHostIp();
    private static final String serverName= MacUtils.getLocalHostName();
    protected BeanHelper daoHelper;
    private static final String JOB_LOG_SEQUENCE = "JOB_LOG_SEQUENCE";

    @Override
    public void execute(JobExecutionContext var1){

        Long jobId = (Long) var1.getJobDetail().getJobDataMap().get("jobId");
        String jobName = (String) var1.getJobDetail().getJobDataMap().get("jobName");
        Timestamp startTime = new Timestamp(System.currentTimeMillis());

        daoHelper = SpringContextUtil.getBean(BeanHelper.class);
        CpublicFunc cpublicFunc  = new CpublicFunc(daoHelper);
        Long jobLogId = cpublicFunc.getSoNbr(SequenceEnum.JOB_LOG_SEQUENCE);

        Map params = new HashMap();
        params.put("JOB_LOG_SONBR",jobLogId);
        try {
            logger.debug("开始执行任务 JOB_NAME:" + jobName);
            doJob(var1, params);
            logger.debug("任务执行完毕 JOB_NAME:" + jobName);
        } catch (JobExecutionException e) {
            logger.error("job执行异常 ID:" + jobId + " JOB_NAME:" + jobName);
        } finally {
            // 记录job运行历史
            Timestamp endTime = new Timestamp(System.currentTimeMillis());
            SystemJobLog jobLog = new SystemJobLog();
            jobLog.setId(jobLogId);
            jobLog.setJobId(Integer.valueOf(jobId + ""));
            jobLog.setJobName(jobName);
            jobLog.setStartTime(startTime);
            jobLog.setEndTime(endTime);
            jobLog.setServerIp(serverIp);
            jobLog.setServerName(serverName);
            DbKeyHolder.setDbKey("master"); // 这里需要单独指定一下数据源，防止跑到其他数据库执行
            SpringContextUtil.getBean(SystemJobLogMapper.class).insert(jobLog);
        }
    }

    public abstract void doJob(JobExecutionContext var1, Map params) throws JobExecutionException;


}
